from fastapi import FastAPI
from starlette.responses import HTMLResponse
import uvicorn
import os
from pyecharts import options as opts
from pyecharts.charts import Pie
from pyecharts.faker import Faker
from pyecharts.charts import Gauge
from ping3 import ping
from pyecharts.components import Table
from pyecharts.options import ComponentTitleOpts
import requests
import json
from ping3 import ping
from typing import Optional


def ping_host(ip):
    """
    获取节点的延迟的作用
    :param node:
    :return:
    """
    ip_address = ip
    response = ping(ip_address)
    #print(response)
    if response is not None:
        delay = int(response * 1000)
        #print(delay, "延迟")
        # 下面两行新增的
    else:
        return 500
    return delay


##定义左右格式
html0='''
<html>
<head>
<meta http-equiv="refresh" content="20">
</head>
<body>
<div id="header" style="clear:both;text-align:center;">
<h2 style="margin-bottom:0;">网络延时大屏实时展示（毫秒）</h2></div>
<div id="container" style="width:1200px"></div>
<div id="left11" style="width:20px;heigth:250px;float:left;"><br></br><br></br><font size="5">北京</font></div>
<div id="left11" style="width:300px;heigth:250px;float:left;">{}</div>
<div id="left11" style="width:300px;heigth:250px;float:left;">{}</div>
<div id="left11" style="width:300px;heigth:250px;float:left;">{}</div>
<div id="left11" style="width:300px;heigth:250px;float:left;">{}</div>
<div id="left11" style="width:300px;heigth:250px;float:left;">{}</div>
<div id="left11" style="clear:both;width:20px;heigth:250px;float:left;"><br></br><br></br><font size="5">南昌</font></div>
<div id="left12" style="width:300px;heigth:250px;float:left;">{}</div>
<div id="left11" style="width:300px;heigth:250px;float:left;">{}</div>
<div id="left11" style="width:300px;heigth:250px;float:left;">{}</div>
<div id="left11" style="width:300px;heigth:250px;float:left;">{}</div>
<div id="left11" style="width:300px;heigth:250px;float:left;">{}</div>
<div id="footer" style="clear:both;text-align:center;">
XX中国IT团队</div>
</div>
</body>
</html>
'''

def remote_ping(web,server):
    
    r = requests.get(web+server)
    return json.loads(r.text)['ping']

def Gauge_template(web,location,name):
    value=remote_ping(web,location)
    d=Gauge(opts.InitOpts(width="300px",height="280px",animation_opts=opts.AnimationOpts(animation=False)),)
    d.add(series_name="网络延时:ms", max_=300,data_pair=[[name, value]],        split_number=5,
          title_label_opts=opts.LabelOpts( font_size=18, color="blue", ),

        axisline_opts=opts.AxisLineOpts(

            linestyle_opts=opts.LineStyleOpts(

                color=[(0.3, "#67e0e3"), (0.7, "#37a2da"), (1, "#fd666d")], width=15

            )

        ),detail_label_opts=opts.LabelOpts(formatter="{value}"),)
    d.set_global_opts(

        legend_opts=opts.LegendOpts(is_show=False),

       

    )
    return d.render_embed()


def ping_host(ip):
    """
    获取节点的延迟的作用
    :param node:
    :return:
    """
    ip_address = ip
    response = ping(ip_address)
    #print(response)
    if response is not None:
        delay = int(response * 1000)
        #print(delay, "延迟")
        # 下面两行新增的
    else:
        return 500
    return delay

app = FastAPI()



@app.get("/pingx")
def pingx():
    #v_nc=ping_host('www.baidu.com')
    #v_hs=ping_host('114.114.114.114')
    return HTMLResponse(content=html0.format(Gauge_template('http://127.0.0.1:8000/ping/','www.baidu.com','慕尼黑'),\
                                             Gauge_template('http://127.0.0.1:8000/ping/','www.sina.com','北京'),\
                                             Gauge_template('http://127.0.0.1:8000/ping/','www.sohu.com','南昌'),\
                                             Gauge_template('http://127.0.0.1:8000/ping/','www.santaihu.com','黄石'),\
                                             Gauge_template('http://127.0.0.1:8000/ping/','www.china.com','上海'),\
                                             Gauge_template('http://gdchina.work:8888/ping/','www.baidu.com','慕尼黑'),\
                                             Gauge_template('http://gdchina.work:8888/ping/','www.sina.com','北京'),\
                                             Gauge_template('http://gdchina.work:8888/ping/','www.sohu.com','南昌'),\
                                             Gauge_template('http://gdchina.work:8888/ping/','www.santaihu.com','黄石'),\
                                             Gauge_template('http://gdchina.work:8888/ping/','www.china.com','上海'),\
                                             
                                             ))
@app.get("/ping/{item_id}")
def read_item(item_id: str, q: Optional[str] = None):
    v_nc=ping_host(item_id)
    return {"item_id": item_id, "ping": v_nc}


if __name__ == "__main__":

    print('当前程序名称为:',os.path.basename(__file__))
    filename=os.path.basename(__file__).split('.')[0]
    
    
    
    

    uvicorn.run(filename+":app", host="0.0.0.0",port=8000,log_level="info")
